package com.yun.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {


    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean//我们无法修改DataSource的源码，所以使用@Bean来创建druidDataSource并且装配到容器中
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    /*后台监控 ,servlet注册到bean*/
    /*springboot内置了servlet容器，没有web.xml,所以我们需要ServletRegistrationBean来代替*/
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        /*账号密码设置*/
        HashMap<String, String> initParameters = new HashMap<>();

        /*key值是固定了*/
        initParameters.put("loginUsername","root");
        initParameters.put("loginPassword","1234");

        /*允许谁能访问*/
        initParameters.put("allow","");

        /*设置初始化参数*/
        bean.setInitParameters(initParameters);
        return bean;
    }

    /*配置过滤器*/
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
           bean.setFilter(new WebStatFilter());

           /*配置我们可以过滤的请求*/
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
                return bean;
    }

}
